/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年11月4日
 */
package com.massyframework.beanskin.runtime.framework;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;

import com.massyframework.beanskin.ModuleIdentifier;
import com.massyframework.beanskin.ModuleRuntimeException;
import com.massyframework.beanskin.SimpleModuleIdentifier;
import com.massyframework.beanskin.customer.Customer;
import com.massyframework.beanskin.util.IOUtils;
import com.massyframework.beanskin.util.exceptioncollect.ExceptionCollectUtils;
import com.massyframework.beanskin.util.localstore.LocalStore;

/**
 * 客户加载器
 * @author huangkh
 *
 */
final class CustomerLoader {
	
	/* 编号，长整型, 默认为0 */
	private static final String ID                       = "id";
	/* 全称，字符串 */
	private static final String NAME                     = "name";
	/* 简称，字符串 */
	private static final String SHORTNAME                = "shortName";
	/* 签名，字符串 */
	private static final String SIGNATURE                = "signature";

	/**
	 * 
	 */
	public CustomerLoader() {
		
	}
	
	public Customer loadCustomer(LocalStore localStore) {
		ModuleIdentifier identifier =
			SimpleModuleIdentifier.createModuleIdentifierWithKernel();
		Path path = localStore.getDeploymentDirectory(identifier)
				.resolve("extends")
				.resolve("customer.properties");
		if (!Files.exists(path)){
			return Customer.newBuilder()
						.id(new Long(0))
						.build();
						
		}
		
		InputStream is = null;
		try {
			is = new FileInputStream(path.toFile());
			Properties props = new Properties();
			props.load(is);
			
			String text = props.getProperty(ID);
			Long id = text == null ? 0 : Long.parseLong(text);
			
			return Customer.newBuilder()
					.id(id)
					.name(props.getProperty(NAME))
					.shortName(props.getProperty(SHORTNAME))
					.signature(props.getProperty(SIGNATURE))
					.build();
		}catch(IOException e) {
			RuntimeException ex = new RuntimeException("load customer.properties failed.", e);
			ExceptionCollectUtils.addException(
					new ModuleRuntimeException(identifier, ex));
			
			return Customer.newBuilder()
					.id(new Long(0))
					.build();
		}finally {
			IOUtils.close(is);
		}
	}

}
